import React, { useState } from 'react';
import {
  Card,
  Table,
  Input,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  InputNumber,
  Select,
  Row,
  Col,
  message,
  Tooltip,
  Badge,
  Progress
} from 'antd';
import { useNavigate } from 'react-router-dom';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  AlertOutlined
} from '@ant-design/icons';
import Layout from '../../components/Layout';

const { Option } = Select;

// 模拟药品数据
const mockMedicines = [
  {
    id: '1',
    name: '布洛芬缓释胶囊',
    spec: '0.3g*20粒/盒',
    category: '止痛药',
    manufacturer: '华北制药',
    stock: 150,
    threshold: 100,
    unit: '盒',
    price: 25.8,
    status: '正常',
  },
  {
    id: '2',
    name: '阿莫西林胶囊',
    spec: '0.5g*24粒/盒',
    category: '抗生素',
    manufacturer: '石药集团',
    stock: 85,
    threshold: 100,
    unit: '盒',
    price: 38.5,
    status: '预警',
  },
  {
    id: '3',
    name: '盐酸氨基葡萄糖片',
    spec: '0.75g*60片/瓶',
    category: '骨骼用药',
    manufacturer: '澳美制药',
    stock: 45,
    threshold: 50,
    unit: '瓶',
    price: 98.0,
    status: '预警',
  },
  {
    id: '4',
    name: '复方感冒灵颗粒',
    spec: '10g*9袋/盒',
    category: '感冒药',
    manufacturer: '三九药业',
    stock: 200,
    threshold: 150,
    unit: '盒',
    price: 22.5,
    status: '正常',
  },
  {
    id: '5',
    name: '硝苯地平缓释片',
    spec: '20mg*30片/盒',
    category: '心血管药',
    manufacturer: '拜耳医药',
    stock: 120,
    threshold: 80,
    unit: '盒',
    price: 45.0,
    status: '正常',
  },
];

const Pharmacy: React.FC = () => {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState('');
  const [medicines, setMedicines] = useState(mockMedicines);
  const [filteredMedicines, setFilteredMedicines] = useState(mockMedicines);
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [currentMedicine, setCurrentMedicine] = useState<any>(null);
  const [form] = Form.useForm();

  // 搜索药品
  const handleSearch = () => {
    const filtered = medicines.filter(
      (med) =>
        med.name.toLowerCase().includes(searchText.toLowerCase()) ||
        med.spec.toLowerCase().includes(searchText.toLowerCase()) ||
        med.manufacturer.toLowerCase().includes(searchText.toLowerCase())
    );
    setFilteredMedicines(filtered);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchText('');
    setFilteredMedicines(medicines);
  };

  // 打开添加药品模态框
  const handleAddMedicine = () => {
    form.resetFields();
    setIsAddModalVisible(true);
  };

  // 打开编辑药品模态框
  const handleEditMedicine = (medicine: any) => {
    setCurrentMedicine(medicine);
    form.setFieldsValue(medicine);
    setIsEditModalVisible(true);
  };

  // 删除药品
  const handleDeleteMedicine = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个药品吗？',
      className: 'apple-modal',
      onOk: () => {
        setMedicines(medicines.filter((med) => med.id !== id));
        setFilteredMedicines(filteredMedicines.filter((med) => med.id !== id));
        message.success('删除成功');
      },
    });
  };

  // 保存新增药品
  const handleSaveNewMedicine = () => {
    form.validateFields().then((values) => {
      const newMedicine = {
        ...values,
        id: Date.now().toString(),
        status: values.stock >= values.threshold ? '正常' : '预警',
      };
      setMedicines([...medicines, newMedicine]);
      setFilteredMedicines([...filteredMedicines, newMedicine]);
      setIsAddModalVisible(false);
      form.resetFields();
      message.success('药品添加成功');
    });
  };

  // 保存编辑药品
  const handleSaveEditMedicine = () => {
    form.validateFields().then((values) => {
      const updatedMedicines = medicines.map((med) =>
        med.id === currentMedicine.id
          ? {
              ...values,
              id: med.id,
              status: values.stock >= values.threshold ? '正常' : '预警',
            }
          : med
      );
      setMedicines(updatedMedicines);
      setFilteredMedicines(
        updatedMedicines.filter(
          (med) =>
            med.name.toLowerCase().includes(searchText.toLowerCase()) ||
            med.spec.toLowerCase().includes(searchText.toLowerCase()) ||
            med.manufacturer.toLowerCase().includes(searchText.toLowerCase())
        )
      );
      setIsEditModalVisible(false);
      form.resetFields();
      message.success('药品更新成功');
    });
  };

  // 药品状态标签颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case '正常':
        return '#34c759';
      case '预警':
        return '#ff9500';
      case '缺货':
        return '#ff3b30';
      default:
        return '#8e8e93';
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '药品名称',
      dataIndex: 'name',
      key: 'name',
      sorter: (a: any, b: any) => a.name.localeCompare(b.name),
      render: (text: string) => <span className="medicine-name">{text}</span>,
    },
    {
      title: '规格',
      dataIndex: 'spec',
      key: 'spec',
      width: 150,
      render: (spec: string) => <span className="medicine-spec">{spec}</span>,
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
      filters: [
        { text: '止痛药', value: '止痛药' },
        { text: '抗生素', value: '抗生素' },
        { text: '骨骼用药', value: '骨骼用药' },
        { text: '感冒药', value: '感冒药' },
        { text: '心血管药', value: '心血管药' },
      ],
      onFilter: (value: string, record: any) => record.category === value,
      width: 100,
      render: (category: string) => (
        <Tag className="category-tag" style={{ backgroundColor: '#007aff', color: 'white' }}>
          {category}
        </Tag>
      ),
    },
    {
      title: '生产厂家',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
      width: 120,
      render: (manufacturer: string) => <span className="manufacturer">{manufacturer}</span>,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      render: (stock: number, record: any) => (
        <Tooltip title={`预警阈值: ${record.threshold}`}>
          <div className="stock-container">
            <Badge
              status={record.status === '预警' || record.status === '缺货' ? 'warning' : 'success'}
              text={
                <div className="stock-info">
                  <span className={`stock-value ${record.status !== '正常' ? 'low-stock-value' : ''}`}>
                    {stock} {record.unit}
                  </span>
                  <div className="progress-container">
                    <Progress
                      percent={(stock / record.threshold) * 100}
                      strokeColor={{
                        '0%': '#007aff',
                        '100%': record.status === '预警' || record.status === '缺货' ? '#ff9500' : '#34c759',
                      }}
                      size="small"
                      className="stock-progress"
                    />
                  </div>
                </div>
              }
            />
          </div>
        </Tooltip>
      ),
      width: 150,
    },
    {
      title: '价格(元)',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => <span className="medicine-price">¥{price}</span>,
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag className="status-tag" style={{ backgroundColor: getStatusColor(status), color: 'white' }}>
          {status}
        </Tag>
      ),
      width: 80,
      filters: [
        { text: '正常', value: '正常' },
        { text: '预警', value: '预警' },
        { text: '缺货', value: '缺货' },
      ],
      onFilter: (value: string, record: any) => record.status === value,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEditMedicine(record)}
            className="apple-button-small-secondary"
          >
            编辑
          </Button>
          <Button
            icon={<DeleteOutlined />}
            size="small"
            danger
            onClick={() => handleDeleteMedicine(record.id)}
            className="apple-button-small-danger"
          >
            删除
          </Button>
        </Space>
      ),
      width: 120,
    },
  ];

  // 药品类别选项
  const categoryOptions = [
    '止痛药',
    '抗生素',
    '骨骼用药',
    '感冒药',
    '心血管药',
    '消化系统药',
    '呼吸系统药',
    '神经系统药',
    '其他',
  ];

  // 药品单位选项
  const unitOptions = ['盒', '瓶', '袋', '支', '片', '粒', '瓶', '袋', '支', '片', '粒'];

  return (
    <Layout title="药品管理" showBackButton>
      <div className="pharmacy-container">
        <div className="page-header">
          <h1 className="page-title">药品管理</h1>
        </div>
        
        <Card className="apple-card search-card">
          {/* 搜索和操作栏 */}
          <Row gutter={16} className="search-actions">
            <Col flex="auto">
              <Space>
                <Input
                  placeholder="搜索药品名称、规格或生产厂家"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  prefix={<SearchOutlined className="search-icon" />}
                  onPressEnter={handleSearch}
                  className="apple-input-search"
                />
                <Button type="primary" onClick={handleSearch} className="apple-button">搜索</Button>
                <Button onClick={handleReset} className="apple-button-secondary">重置</Button>
              </Space>
            </Col>
            <Col>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAddMedicine} className="apple-button">
                添加药品
              </Button>
            </Col>
          </Row>
        </Card>

        {/* 药品列表 */}
        <Card className="apple-card medicines-table-card">
          <Table
            columns={columns}
            dataSource={filteredMedicines}
            rowKey="id"
            pagination={{ pageSize: 10 }}
            scroll={{ x: 1200 }}
            className="pharmacy-table"
            rowClassName={(record) => record.status !== '正常' ? 'low-stock-row' : ''}
          />
        </Card>
      </div>

      {/* 添加药品模态框 */}
      <Modal
        title="添加药品"
        open={isAddModalVisible}
        onOk={handleSaveNewMedicine}
        onCancel={() => setIsAddModalVisible(false)}
        width={600}
        className="apple-modal"
      >
        <Form form={form} layout="vertical" className="medicine-form">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="药品名称"
                rules={[{ required: true, message: '请输入药品名称' }]}
              >
                <Input placeholder="请输入药品名称" className="apple-input" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="spec"
                label="规格"
                rules={[{ required: true, message: '请输入药品规格' }]}
              >
                <Input placeholder="请输入药品规格" className="apple-input" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="类别"
                rules={[{ required: true, message: '请选择药品类别' }]}
              >
                <Select placeholder="请选择药品类别" className="apple-select">
                  {categoryOptions.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="manufacturer"
                label="生产厂家"
                rules={[{ required: true, message: '请输入生产厂家' }]}
              >
                <Input placeholder="请输入生产厂家" className="apple-input" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="unit"
                label="单位"
                rules={[{ required: true, message: '请选择单位' }]}
              >
                <Select placeholder="请选择单位" className="apple-select">
                  {unitOptions.map((unit) => (
                    <Option key={unit} value={unit}>
                      {unit}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="stock"
                label="库存数量"
                rules={[{ required: true, message: '请输入库存数量' }]}
              >
                <InputNumber
                  placeholder="请输入库存数量"
                  min={0}
                  style={{ width: '100%' }}
                  className="apple-input-number"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="threshold"
                label="预警阈值"
                rules={[{ required: true, message: '请输入预警阈值' }]}
              >
                <InputNumber
                  placeholder="请输入预警阈值"
                  min={0}
                  style={{ width: '100%' }}
                  className="apple-input-number"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格' }]}
              >
                <InputNumber
                  addonBefore="¥"
                  placeholder="请输入价格"
                  min={0}
                  step={0.1}
                  style={{ width: '100%' }}
                  className="apple-input-number"
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 编辑药品模态框 */}
      <Modal
        title="编辑药品"
        open={isEditModalVisible}
        onOk={handleSaveEditMedicine}
        onCancel={() => setIsEditModalVisible(false)}
        width={600}
        className="apple-modal"
      >
        <Form form={form} layout="vertical" className="medicine-form">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="药品名称"
                rules={[{ required: true, message: '请输入药品名称' }]}
              >
                <Input placeholder="请输入药品名称" className="apple-input" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="spec"
                label="规格"
                rules={[{ required: true, message: '请输入药品规格' }]}
              >
                <Input placeholder="请输入药品规格" className="apple-input" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="类别"
                rules={[{ required: true, message: '请选择药品类别' }]}
              >
                <Select placeholder="请选择药品类别" className="apple-select">
                  {categoryOptions.map((category) => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="manufacturer"
                label="生产厂家"
                rules={[{ required: true, message: '请输入生产厂家' }]}
              >
                <Input placeholder="请输入生产厂家" className="apple-input" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="unit"
                label="单位"
                rules={[{ required: true, message: '请选择单位' }]}
              >
                <Select placeholder="请选择单位" className="apple-select">
                  {unitOptions.map((unit) => (
                    <Option key={unit} value={unit}>
                      {unit}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="stock"
                label="库存数量"
                rules={[{ required: true, message: '请输入库存数量' }]}
              >
                <InputNumber
                  placeholder="请输入库存数量"
                  min={0}
                  style={{ width: '100%' }}
                  className="apple-input-number"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="threshold"
                label="预警阈值"
                rules={[{ required: true, message: '请输入预警阈值' }]}
              >
                <InputNumber
                  placeholder="请输入预警阈值"
                  min={0}
                  style={{ width: '100%' }}
                  className="apple-input-number"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格' }]}
              >
                <InputNumber
                  addonBefore="¥"
                  placeholder="请输入价格"
                  min={0}
                  step={0.1}
                  style={{ width: '100%' }}
                  className="apple-input-number"
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </Layout>
  );
};

export default Pharmacy;